package com.suishoupai.xmb.controller;

import com.github.pagehelper.Page;
import com.suishoupai.xmb.entity.AjaxMessage;
import com.suishoupai.xmb.entity.OrderStatusEnum;
import com.suishoupai.xmb.exception.XmbException;
import com.suishoupai.xmb.service.OrdersService;
import com.suishoupai.xmb.utils.PageUtil;
import com.suishoupai.xmb.utils.SecurityUserUtil;
import com.suishoupai.xmb.utils.ValidateUtil;
import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * Created by caojian on 2017/4/13.
 */
@Controller
@RequestMapping("/sale/orders")
@PreAuthorize("hasRole('ROLE_SALE')")
public class SaleOrdersController {
    @Autowired
    private OrdersService ordersService;

    @GetMapping("")
    public Object index(@RequestParam Map map, Model model) {
        int status = MapUtils.getIntValue(map, "status", OrderStatusEnum.WAIT_SEND.getValue());
        ValidateUtil.in(status, OrderStatusEnum.WAIT_SEND.getValue(), OrderStatusEnum.COMPLETE.getValue());
        PageUtil.startPage(map);
        long saleId = SecurityUserUtil.getUser().getId();
        Page page = (Page) ordersService.getOrdersListBySaleIdAndStatus(saleId, status);
        model.addAttribute("status", status);
        model.addAttribute("ordersList", page.toPageInfo());
        return "sale-orders-list";
    }

    /**
     * 完成发货
     *
     * @return
     */
    @PostMapping("/{ordersId}")
    @ResponseBody
    public Object complete(@PathVariable("ordersId") long ordersId) {
        long saleId = SecurityUserUtil.getUser().getId();
        try {
            ordersService.orderComplete(ordersId, saleId);
        } catch (XmbException e) {
            if (e.isRepeatRequest()) {
                return AjaxMessage.newSuccessMsg();
            }
            return AjaxMessage.newErrorHintMsg(e.getError());
        }
        return AjaxMessage.newSuccessMsg();
    }
}
